import Core.Basic
from Core.package import *






class Worker_Thread(QThread):
    thread_task_data = Signal(dict)
    current_handle = Signal(str)
    current_url = Signal(str)
    current_title = Signal(str)
    def __init__(self, parent = None):
        super().__init__(parent)
        self.task_data = dict()
    
    def run(self):
        try:            
            options = Options()
            options.add_experimental_option("debuggerAddress", "127.0.0.1:9652")
            service = Service()
            Core.Basic.GlobalVar.driver = WebDriver(options=options, service=service)
            Core.Basic.GlobalVar.wait = WebDriverWait(driver=Core.Basic.GlobalVar.driver,timeout=10)
            Core.Basic.GlobalVar.actions = ActionChains(driver=Core.Basic.GlobalVar.driver)
            
            driver = Core.Basic.GlobalVar.driver
            
            if isinstance(driver,WebDriver):
                self.finished.emit()
            UpdateCount = int(0)
            while True:

                try:
                    self.current_handle.emit(driver.current_window_handle)
                    self.current_url.emit(driver.current_url)
                    self.current_title.emit(driver.title)
                    
                except Exception as e:
                    self.current_handle.emit("None")
                    self.current_url.emit("None")
                    self.current_title.emit("None")
                    
                finally:
                    UpdateCount += 1
                    self.task_data['updatecount'] = UpdateCount
                    
                    # print(f"【提示】:当前线程正在更新浏览器状态信息,当前更新次数: {UpdateCount}")
                
                # 下方设置的延时是为了防止浏览器状态更新过快导致信号发送过于频繁
                Delay = float(3)
                QThread.sleep(Delay)

                
            
        except Exception as e:
            print(f"提示 : 员工线程任务发生错误!\n\
                    错误信息: {e}")


        # 线程任务完成，会自动发送信号的,无需手动发送,手动发送可能会导致发送两遍信号.
        # self.finished.emit()
    def __delattr__(self, name):
        print(f"提示 : 子任务子线程运行结束!正在销毁资源 {self}")
        return super().__delattr__(name)
    

class Staff_Init_Selenium_Frame(QObject):
    Start_Task = Signal()   # 任务开始信号,启动任务时,请发送此信号
    Task_Finish = Signal()   # 任务完成信号,任务结束时候,请发送此信号
    Current_Completion_Process = Signal(int)
    Emergency_Stop = Signal()  # 紧急停止信号
    OnlyRun = Signal()  # 仅运行信号

    def __init__(self, parent=None):
        super().__init__(parent)
        self.Start_Task.connect(self.RunTask)
        
    @Slot(str)
    def slot_fun(self,text):
        print(f"我是槽函数,我是 {text}")

    # 设置员工属性
    def Set_Staff_Attribute(self,**kwargs):
        """设置员工对象的属性，用于后续任务执行
        """
        for key, value in kwargs.items():
            setattr(self, key, value)
        print(f"已设置属性: {kwargs.keys()}")

    def RunTask(self):

        # 获取需要操作的 主线程 窗口的 UI 对象
        # 使用 self.parent() 获取父对象
        self.parent_widget = self.parent()
        if self.parent_widget is None:
            print(f"提示 : 父对象为空!\n请将创建员工对象时,将父对象作为参数传入!")
            return
        # 获取 任务按钮 UI 控件对象
        self.task_button_object_name = "pushButton_init_selenium_frame"
        self.task_button : QPushButton = self.parent().findChild(QPushButton,self.task_button_object_name)
        if self.task_button is None:
            print(f"提示 : 程序无法找到 {self.task_button_object_name} 对应的按钮!")
            print(f"提示 : 子任务结束!")
            return
        self.label_current_handle_object_name = "label_browser_current_handle"
        self.label_current_handle : QLabel = self.parent().findChild(QLabel,self.label_current_handle_object_name)
        if self.label_current_handle is None:
            print(f"提示 : 程序无法找到 {self.label_current_handle_object_name} 对应的标签!")
            print(f"提示 : 子任务结束!")
        self.label_current_url_object_name = "label_browser_current_url"
        self.label_current_url : QLabel = self.parent().findChild(QLabel,self.label_current_url_object_name)
        if self.label_current_url is None:
            print(f"提示 : 程序无法找到 {self.label_current_url_object_name} 对应的标签!")
            print(f"提示 : 子任务结束!")
        self.label_current_title_object_name = "label_browser_current_title"
        self.label_current_title : QLabel = self.parent().findChild(QLabel,self.label_current_title_object_name)
        if self.label_current_title is None:
            print(f"提示 : 程序无法找到 {self.label_current_title_object_name} 对应的标签!")
            print(f"提示 : 子任务结束!")

        # 创建子线程
        self.workerthread = Worker_Thread()



        # 绑定信号
        self.workerthread.finished.connect(lambda : QMessageBox.information(self.parent_widget,"提示",f"初始化 Selenium Frame 框架成功!"))
        # self.workerthread.finished.connect(lambda : self.Task_Finish.emit())    # 子线程运行结束代表该员工类的任务结束
        # self.workerthread.finished.connect(lambda : self.workerthread.quit())   # 线程结束，销毁线程
        # self.workerthread.finished.connect(lambda : self.deleteLater())
        self.workerthread.finished.connect(lambda : self.task_button.setEnabled(True))
        self.workerthread.current_handle.connect(lambda text:self.label_current_handle.setText(text))
        self.workerthread.current_url.connect(lambda text:self.label_current_url.setText(text))
        self.workerthread.current_title.connect(lambda text:self.label_current_title.setText(text))


        # 启动子线程,开始执行任务
        self.task_button.setEnabled(False)
        self.workerthread.start()
        

        


















if __name__ == "__main__":
    import sys
    from PySide6.QtWidgets import QApplication
    app = QApplication(sys.argv)
    # 编写 控制台 程序
    staff = Staff_Init_Selenium_Frame(app)
    staff.RunTask()
    
    sys.exit(app.exec_())